package com.hishop.controller;

import com.alibaba.fastjson.TypeReference;
import com.hishop.common.utils.R;
import com.hishop.common.vo.MemberResponseVo;
import com.hishop.constant.JwtServerConstant;
import com.hishop.feign.MemberFeignService;
import com.hishop.vo.UserLoginVo;
import com.hishop.vo.UserRegistVo;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
public class LoginController {

    @Resource
    MemberFeignService memberFeignService;

    /**
     * 注册
     */
    @PostMapping("/register")
    public String register(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes redirectAttributes, HttpSession session) {
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:localhost:20000/reg.html";
        }
        R r = memberFeignService.regist(vo);
        if (r.getCode() == 0) {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", r.getData(new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:/login.html";
        } else {
            return "redirect:localhost:20000/reg.html";
        }

    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        Object attribute = session.getAttribute(JwtServerConstant.LOGIN_USER);
        if (attribute==null){
            return "index";
        }else {
            return "redirect:http://localhost:10010";
        }
    }

    /**
     * 登录
     *
     * @param vo
     * @return
     */
    @PostMapping("/login")
    public String login(UserLoginVo vo,RedirectAttributes redirectAttributes,HttpSession session) {

        R login = memberFeignService.login(vo);
        if (login.getCode()==0){
            MemberResponseVo data = login.getData("data",new TypeReference<MemberResponseVo>(){});
            session.setAttribute(JwtServerConstant.LOGIN_USER,data);
            return "redirect:http://localhost:10010";
        }else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://localhost:20000/login.html";
        }
    }
}
